package com.daydr3am.thenation;

import java.io.IOException;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Vector;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.entity.mime.MultipartEntity;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import com.coe3.data.AllIntent;
import com.coe3.data.Information;
import com.coe3.data.NewData;
import com.coe3.data.PathManager;
import com.coe3.data.PdfData;
import com.coe3.datahandler.BaseActivity;
import com.coe3.datahandler.DrawableManager;
import com.coe3.datahandler.HttpConnection;
import com.coe3.datahandler.ParserXMLHandler;
import com.coe3.datahandler.ParserXMLHandler.ElementData;
import com.coe3.handle.DecompressAsync;
import com.coe3.handle.NewsDownloadAsync;
import com.coe3.handle.PDFDownloadAsync;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

public class Store {
	
	public static final String KEY_IS_OFFLINE = "KEY_IS_OFFLINE";

	private final int[] mIvs = {R.id.store_iv_00, 
								R.id.store_iv_01, 
								R.id.store_iv_02, 
								R.id.store_iv_03, 
								R.id.store_iv_04, 
								R.id.store_iv_05, 
								R.id.store_iv_06};
	
	private final int[] mBtns = {	R.id.store_btn_00, 
									R.id.store_btn_01, 
									R.id.store_btn_02, 
									R.id.store_btn_03, 
									R.id.store_btn_04, 
									R.id.store_btn_05, 
									R.id.store_btn_06};
	
	private final int[] mTxts = {	R.id.store_txt_00, 
									R.id.store_txt_01, 
									R.id.store_txt_02, 
									R.id.store_txt_03, 
									R.id.store_txt_04, 
									R.id.store_txt_05, 
									R.id.store_txt_06};
	
	private final int[] mIvsPDF = {	R.id.store_iv_pdf_00, 
									R.id.store_iv_pdf_01, 
									R.id.store_iv_pdf_02};

	private final int[] mBtnsPDF = {R.id.store_btn_pdf_00, 
									R.id.store_btn_pdf_01, 
									R.id.store_btn_pdf_02};
	
	private final int[] mTxtsPDF = {R.id.store_txt_pdf_00, 
									R.id.store_txt_pdf_01, 
									R.id.store_txt_pdf_02};
	
	public static final String KEY_PATH = "KEY_PATH";
	public static final String KEY_PACKAGE = "KEY_PACKAGE";
	public static final String KEY_URL_DOWNLOAD = "KEY_URL_DOWNLOAD";
	
//	"http://www.nationmultimedia.com/new/rss/ipad_v2/offline/2012-02-21.zip" 
//	"http://www.nationmultimedia.com/new/rss/ipad_v2/offline/2012-02-21/coverpage_2012-02-21.jpg";
	private final String mUrl = "http://www.nationmultimedia.com/new/rss/ipad_v2/offline/";
	private final String Str_Coverpage = "coverpage_";
	private final int MAX_NEWS = 7;
	private final int MAX_PDF = 3;
	
	private Activity mActivity;
	
	public static Store mInstanceStore;
	
	public static Store getInstance() {
		if(mInstanceStore == null)
			mInstanceStore = new Store();
		
		return mInstanceStore;
	}
	
	public void initial(Activity activity) {
		this.mActivity = activity;
		setData(this);
		
		loadDataPDF();
	}
	
	public void loadDataPDF() {
		String url = "http://www.nationmultimedia.com/home/admin/exchange/upload_issue/rss/upload_pdf_issue.xml";
  		startConnection( url, "", HttpConnection.GET, -1, null );
	}
	
	public void setData(final Store store) {
		new Handler().post(new Runnable() {
			
			@SuppressLint("SimpleDateFormat")
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(new Date());
				for (int i = 0; i < MAX_NEWS; i++) {
					if(i == 0)
						calendar.add(Calendar.DAY_OF_WEEK, 0);
					else
						calendar.add(Calendar.DAY_OF_WEEK, -1);
					
					SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
					String date = dateFormat.format(calendar.getTime());
					DrawableManager.getInstance().fetchDrawableOnThread( getUrlCoverPage(date), ((ImageView) mActivity.findViewById(mIvs[i])), R.drawable.ic_empty );
					((TextView) mActivity.findViewById(mTxts[i])).setText(date);
					mActivity.findViewById(mBtns[i]).setOnClickListener(new clickToDownloadAvaliable(getUrlDownload(date), store, false, null));
				}//end for
			}
		});
	}
	
	public final class clickToDownloadAvaliable implements View.OnClickListener {
		
		private String url;
		private Store store;
		private Boolean isPDF;
		private String fileName;
		
		public clickToDownloadAvaliable(String url, Store store, Boolean isPDF, String fileName) {
			// TODO Auto-generated constructor stub
			this.url = url;
			this.store = store;
			this.isPDF = isPDF;
			this.fileName = fileName;
		}
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Log.e(Information.TAG_DBUG, "data.url: " + url);
			new NewsDownloadAsync( mActivity, store, isPDF, fileName ).execute(url);
		}
	}
	
	public final class clickToDownloadSpecial implements View.OnClickListener {
		
		private PdfData data;
		
		public clickToDownloadSpecial(PdfData data) {
			// TODO Auto-generated constructor stub
			this.data = data;
		}
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			new PDFDownloadAsync(mActivity, data.title).execute(data.linkThumb, data.linkPdf);
		}
	}
	
	public final class clickToOpenPDF implements View.OnClickListener {
		
		private String pathPDF;
		
		public clickToOpenPDF(String pathPDF) {
			// TODO Auto-generated constructor stub
			this.pathPDF = pathPDF;
		}
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			AllIntent.openPDF(mActivity, pathPDF);
		}
	}
	
	public String getUrlDownload(String date) {
		return mUrl + date + PathManager.Extension_ZIP;
	}
	
	public String getUrlCoverPage(String date) {
		return mUrl + date + "/" + Str_Coverpage + date + PathManager.Extension_JPG;
	}
	
	public void onDownloadDidFinish(String filepath ) {

		try {
			String zipFilename = PathManager.getExternalCacheDir(mActivity, false) + filepath; 
			String unzipLocation = PathManager.getExternalCacheDir(mActivity, false) + filepath.replace(PathManager.Extension_ZIP, ""); 

			new DecompressAsync(mActivity, zipFilename, unzipLocation).execute(null, null, null);
		} catch( Exception e ) {
//			activity.showAlertBox("Attention", "There is no network connection right now. Please try again later.");
		}
	}
	
//	
//	//////////////////////////////////////////////////////////////////////////
//	// Progress Dialog
//	//////////////////////////////////////////////////////////////////////////
//	
//	private static ProgressDialog mProgressDialog = null;
//	private static ProgressDialog mDownloadDialog = null;
//	
//	public static ProgressDialog getInstanceProgressDialong(BaseActivity mActivity) {
//		if (mProgressDialog == null) {
//			mProgressDialog = new ProgressDialog(mActivity);
//			mProgressDialog.setIndeterminate(true);
//			mProgressDialog.setMessage( " Please wait. " );
//			mProgressDialog.setCancelable( false );
//		}//end if
//		
//		return mProgressDialog;
//	}
//	
//	public static void setNullInstanceProgressDialong() {
//		if (mProgressDialog != null) {
//			mProgressDialog = null;
//		}//end if
//	}
//	
//	public static ProgressDialog getInstanceDownloadDialog(BaseActivity mActivity) {
//		if (mDownloadDialog == null) {
//			mDownloadDialog = new ProgressDialog(mActivity);
//	    	mDownloadDialog.setMessage(" Downloading ... ");
//	    	mDownloadDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//	    	mDownloadDialog.setCancelable(false);
//	    	mDownloadDialog.setProgress(0);
//	    	mDownloadDialog.setMax(100);
//		}//end if
//		
//		return mDownloadDialog;
//	}
//	
//	public static void setNullInstanceDownloadDialog() {
//		if (mDownloadDialog != null) {
//			mDownloadDialog = null;
//		}//end if
//	}
//	
//	public static void dismissProgress(BaseActivity mActivity) {
//		// You can't be too careful.
//		if (getInstanceProgressDialong(mActivity) != null && getInstanceProgressDialong(mActivity).isShowing() && getInstanceProgressDialong(mActivity).getWindow() != null) {
//			try {
//				getInstanceProgressDialong(mActivity).dismiss();
//			} catch ( IllegalArgumentException ignore ) { ; }
//		}
//		setNullInstanceProgressDialong();
//	}
//	
//	public static void dismissDownload(BaseActivity mActivity) {
//		// You can't be too careful.
//		if (getInstanceDownloadDialog(mActivity) != null && getInstanceDownloadDialog(mActivity).isShowing() && getInstanceDownloadDialog(mActivity).getWindow() != null) {
//			try {
//				getInstanceDownloadDialog(mActivity).dismiss();
//			} catch ( IllegalArgumentException ignore ) { ; }
//		}
//		setNullInstanceDownloadDialog();
//	}
	
	@SuppressLint("HandlerLeak")
	public void startConnection( String url, String data , int method, final int handlerType, final MultipartEntity entity ) {
		Log.e("chud", "url: " + url);
		Log.e("chud", "data: " + data);
		
		Handler handler = new Handler() {
			public void handleMessage(Message message) {
				switch ( message.what ) {
				case HttpConnection.DID_START:
						TheNationMain.getInstanceProgressDialong(mActivity).show();
					break;
				
				case HttpConnection.DID_SUCCEED:
					try {
						Log.e("chud", "(String)message.obj: " + (String)message.obj);
						startParseXMLResponse( (String)message.obj, handlerType );
					} catch ( Exception e ) {
						Log.e( "Connection Exception", "XML Pasing Excpetion : " + e );
						TheNationMain.dismissProgress(mActivity);
					}
					
					break;
				
				case HttpConnection.DID_ERROR:
					Log.e( "Connection Error", "HTTP Connection did error : " + message.obj );
					BaseActivity.showAlertBox(mActivity,  "Connection Error!!!", "Please try again." );
					TheNationMain.dismissProgress(mActivity);
					break;
				}	
			}
		};

		HttpConnection connection = new HttpConnection(handler);
		if( entity != null )
			connection.setMultipartEntity( entity );
		connection.create(method, url, data);
	}

	public void startParseXMLResponse( String response, int handlerType ) throws SAXException, ParserConfigurationException, IOException {
		
		SAXParserFactory spf = SAXParserFactory.newInstance();
		SAXParser sp = spf.newSAXParser();
		XMLReader xr = sp.getXMLReader();
		
		ParserXMLHandler parser = null;
		Handler handler = handlerInformation(handlerType);
		parser = new ParserXMLHandler( handler );
		
		StringReader sr = new StringReader(response);
		InputSource is = new InputSource(sr);
		
		xr.setContentHandler(parser);
		xr.parse(is);
	}
	
	private static Vector<PdfData> mListDatas = new Vector<PdfData>();
	private PdfData mItem = null;
	@SuppressLint("HandlerLeak")
	public Handler handlerInformation(final int handlerType) {
		
		Handler mHandler = new Handler() {
			public void handleMessage( Message message ) {
				ElementData data = ( ElementData )message.obj;
				switch( message.what ) {
					case ParserXMLHandler.START_DOCUMENT:
						
						mListDatas.removeAllElements();
						
						break;
						
					case ParserXMLHandler.DID_START_ELEMENT:
						
						if( data.name.equalsIgnoreCase(NewData.TAG_ITEM) ) 
						{
							mItem = new PdfData();
						}//end if
						
						break;
						
					case ParserXMLHandler.DID_FINISH_ELEMENT:
						
						if( data.name.equalsIgnoreCase(PdfData.TAG_TITLE) ) 
						{
							mItem.title = Information.setData(data.value, Information.STR_EMPTY);
						} 
						else if( data.name.equalsIgnoreCase(PdfData.TAG_LINK_PDF) ) 
						{
							mItem.linkPdf = Information.setData(data.value, Information.STR_EMPTY);
						}
						else if( data.name.equalsIgnoreCase(PdfData.TAG_LINK_THUMB) ) 
						{
							mItem.linkThumb = Information.setData(data.value, Information.STR_EMPTY);
						}
						else if( data.name.equalsIgnoreCase(PdfData.TAG_ITEM) ) 
						{
							mListDatas.add(mItem);
							mItem = null;
						}//end if
						
						break;
						
					case ParserXMLHandler.END_DOCUMENT:
						
						TheNationMain.dismissProgress(mActivity);
						setPDF(mListDatas);
						
						break;
				}
			}
		};
			
		return mHandler;
	}
	
	public void setPDF(Vector<PdfData> listDatas) {
//		File files = new File(NewsDownloadAsync.getExternalCacheDir(mActivity, true));
//		File root = files.listFiles()[0];
//		Information.logDEBUG("getAbsolutePath: " + root.getAbsolutePath());
		
		for (int i = 0; i < MAX_PDF; i++) {
			DrawableManager.getInstance().fetchDrawableOnThread( listDatas.get(i).linkThumb, ((ImageView) mActivity.findViewById(mIvsPDF[i])), R.drawable.ic_empty );
			((TextView) mActivity.findViewById(mTxtsPDF[i])).setText(listDatas.get(i).title);
//			mActivity.findViewById(mBtnsPDF[i]).setOnClickListener(new clickToDownloadAvaliable(listDatas.get(i).linkPdf, this, true, PathManager.combineExtension(listDatas.get(i).title, PathManager.Extension_PDF)));
			
			mActivity.findViewById(mBtnsPDF[i]).setOnClickListener(new clickToDownloadSpecial(listDatas.get(i)));
			//Click to open PDF.
//			mActivity.findViewById(mBtnsPDF[i]).setOnClickListener(new clickToOpenPDF(root.getAbsolutePath()));
		}//end for
	}
}
